﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace JQMergeFramework
{
    public class UIMarquee : MonoBehaviour
    {
        public GameObject goItem;

        //可同时显示的最大行数
        public int lineNum = 3;
        
        private float itemH = 70;

        public BhvEasyPool objPool;

        public Transform showNodeTrans;
        
        //是否开始
        private bool isRun = false;

        //显示间隔基数
        private float intervalCfg = 180f;
        
        //当前显示间隔计时
        private float intervalCur = 3;

        //下一条信息显示的行数
        private int nextLineIndex = 0;
        

        //提现项
        private IList<MarqueeCfg> marqueeInfo;



        private float canvasWidth;

        private void Start()
        {
            canvasWidth = this.GetComponent<RectTransform>().rect.size.x;
            
            itemH = goItem.GetComponent<RectTransform>().sizeDelta.y + 20;
            
            goItem.SetActive(false);
            
            marqueeInfo = TableConfig.Instance.MarqueeCfgList;
            Open();
        }


        public void Open()
        {
            isRun = false;
            CommonFun.DelayCallback(() => { isRun = true; }, 2);
        }
        
        private void ShowItem()
        {
            GameObject item = objPool.Get();

            if (item != null)
            {
                //坐标
                float y = (nextLineIndex * itemH) + showNodeTrans.position.y;

                //重置下一行
                if (nextLineIndex == 0)
                {
                    nextLineIndex = Random.Range(1, lineNum);
                }
                else if (nextLineIndex == lineNum - 1)
                {
                    nextLineIndex = Random.Range(0, lineNum - 1);
                }
                else if (Random.Range(0, 1f) < 0.5f)
                {
                    nextLineIndex = Random.Range(0, nextLineIndex);
                }
                else
                {
                    nextLineIndex = Random.Range(nextLineIndex + 1, lineNum);
                }
                
                item.transform.SetParent(showNodeTrans.transform);
                
                //随机提现项
                int index = Random.Range(0, marqueeInfo.Count);
                item.GetComponent<UIMarqueeItem>().Refresh(marqueeInfo[index], objPool,
                    new Vector3(canvasWidth, y, 0),
                    new Vector3((-canvasWidth / 2), 0, 0));
            }
        }

        private void Update()
        {
            if (!isRun) return;

            if (intervalCur > 0)
            {
                intervalCur -= Time.deltaTime;
            }
            else
            {
                ShowItem();
                intervalCur = intervalCfg;
            }
        }
        
    }

}